package http;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpRequestUtils {

  static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);

  private static CloseableHttpClient client = HttpClientBuilder.create().build();

  public static void main(String[] args) {

//    doPostCanRetry("localhost", "{ \"hello word\" : \" hah\" }", 1);
    String s = doGetCanRetry("http://dts-cluster-193.ennew.com/jobs/00000000000000000000000000000000/execution-result",
            new HashMap<>(), 1);
    System.out.println(s);
  }

  /**
   * 可能抛出运行时异常
   *
   * @param url
   * @param header
   * @param retryTimes
   * @return
   */
  public static String doGetCanRetry(String url, Map<String, String> header, int retryTimes) {
    if (header != null && header.size() > 0) {
      List<String> kv = Lists.newLinkedList();
      for (Map.Entry<String, String> headerEntity : header.entrySet()) {
        kv.add(headerEntity.getKey() + "=" + headerEntity.getValue());
      }
      url += "?" + StringUtils.join(kv.iterator(), "&");
    }
    HttpGet request = new HttpGet(url);
    return httpCanRetry(request, retryTimes);
  }

  /**
   * 可能抛出运行时异常
   */
  public static String doPostCanRetry(String url, String requestJson, int retryTimes) {
    HttpPost request = new HttpPost(url);
    if (StringUtils.isNotBlank(requestJson)) {
      //解决中文乱码问题
      StringEntity entity = new StringEntity(requestJson, "utf-8");
      entity.setContentType("application/json;charset=UTF-8");
      request.setEntity(entity);
    }
    return httpCanRetry(request, retryTimes);
  }

  public static String httpCanRetry(HttpRequestBase request, int retryTimes) {
    for (int i = 1; i <= retryTimes; i++) {
      HttpResponse response;
      try {
        response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
          //成功响应直接返回
          return EntityUtils.toString(response.getEntity(), "UTF-8");
        } else {
          if (retryTimes == i) {
            logger.error("send http request failed {}. Unexpected code: {}", request, response);
            throw new RuntimeException("send http request failed. Unexpected code: " + response);
          } else {
            logger.warn("send http request failed {}. Unexpected code: {}", request, response);
          }
        }
      } catch (Exception e) {
        if (retryTimes == i) {
          logger.error("send http request failed {}.", request, e);
          throw new RuntimeException("send http request failed. "
                  + request, e);
        } else {
          logger.warn("send http request failed {}.", request, e);
        }
      }
    }
    return null;
  }

}
